package com.leetcode.sorts.tree;

import java.util.*;

/**
 * @Author: WuPeng
 * @Date: 2021/6/2 5:09 下午
 *
 * 145.二叉树的后序遍历
 *
 */
public class PostOrder_145 {

    public static List<Integer> postOrderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        postOrder(res, root);
        return res;
    }

    private static void postOrder(List<Integer> res, TreeNode node) {
        if (node == null){
            return;
        }
        postOrder(res, node.left);
        postOrder(res, node.right);
        res.add(node.val);
    }

    public static List<Integer> postOrderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        while (!deque.isEmpty()){
            TreeNode node = deque.pop();
            res.add(node.val);
            if (node.left != null){
                deque.push(node.left);
            }
            if (node.right != null){
                deque.push(node.right);
            }
        }
        Collections.reverse(res);
        return res;
    }

    public static void main(String[] args) {
        TreeNode left = new TreeNode(2);
        TreeNode right = new TreeNode(3,left, null);
        TreeNode root = new TreeNode(1,null,right);

        List<Integer> integers_1 = postOrderTraversal(root);
        List<Integer> integers_2 = postOrderTraversal2(root);

        System.out.println(Arrays.toString(integers_1.toArray()));
        System.out.println(Arrays.toString(integers_2.toArray()));
    }

}
